﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using LevenBlog.Core.Data;
using LevenBlog.Core.Entities;
using LevenBlog.Core.Utils;
using LevenBlog.Core.Service;
using LevenBlog.Core.Mvc;
using LevenBlog.Core.Cache;
using LevenBlog.Core.User;

namespace LevenBlog.Web.Controllers
{
    [HandleBlogError]
    [ValidateInput(false)]
    public class BlogController : BlogBaseController
    {
        public BlogController()
        {
            CacheItem<IList<lb_blog>> sideBlogs = ObjectCache.GetItem<IList<lb_blog>>("blog_side_list");
            if (sideBlogs == null)
            {
                sideBlogs = new CacheItem<IList<lb_blog>>();
                sideBlogs.Key = "blog_side_list";
                sideBlogs.Object = Blog.Get(Provider, 10, 1, BlogState.Show);
                ObjectCache.Insert<IList<lb_blog>>(sideBlogs);
            }
            CacheItem<IList<lb_comment>> sideComments = ObjectCache.GetItem<IList<lb_comment>>("comment_side_list");
            if (sideComments == null)
            {
                sideComments = new CacheItem<IList<lb_comment>>();
                sideComments.Key = "comment_side_list";
                sideComments.Object = LevenBlog.Core.Service.Comment.Get(Provider, 10, 1, CommentState.Show);
                ObjectCache.Insert<IList<lb_comment>>(sideComments);
            }
            ViewData["friendlinks"] = FriendLink.Get(Provider).Where(f => f.isshow == true && f.isindex == true).ToList();
            ViewData["sideblogs"] = sideBlogs.Object;
            ViewData["sidecomments"] = sideComments.Object;
            ViewData["sidearchive"] = LevenBlog.Core.Service.Archive.Get(Provider);
            ViewData["selectdate"] = DateTime.Now;
            ViewData["linkdate"] = new List<DateTime>();
            ViewData["loginuser"] = Membership.User;
            ViewData["authority"] = Membership.Authority;
            ViewData["pagesize"] = Config.Get(Provider).blogpage;
            ViewData["commentpagesize"] = Config.Get(Provider).commentpage;
        }

        public ActionResult Index(int? page)
        {
            return List(null, page);
        }

        public ActionResult List(int? category, int? page)
        {
            category = category ?? 0;
            page = page ?? 1;
            if (page.Value < 1)
                page = 1;
            if (category.Value < 1)
            {
                ViewData["recordcount"] = Blog.Count(Provider);
                if (page.Value == 1)
                {
                    CacheItem<IList<lb_blog>> indexBlogList = ObjectCache.GetItem<IList<lb_blog>>("index_blog_list");
                    if (indexBlogList == null)
                    {
                        indexBlogList = new CacheItem<IList<lb_blog>>();
                        indexBlogList.Key = "index_blog_list";
                        indexBlogList.Object = Blog.Get(Provider, Config.Get(Provider).blogpage, page.Value, BlogState.Show);
                        ObjectCache.Insert<IList<lb_blog>>(indexBlogList);
                    }
                    ViewData.Model = indexBlogList.Object;
                }
                else
                {
                    ViewData.Model = Blog.Get(Provider, Config.Get(Provider).blogpage, page.Value, BlogState.Show);
                }
            }
            else
            {
                ViewData["recordcount"] = Blog.Count(Provider, category.Value);
                ViewData.Model = Blog.Get(Provider, category.Value, Config.Get(Provider).blogpage, page.Value, BlogState.Show);
            }
            ViewData["calendardata"] = CalendarCache.Get(Provider, DateTime.Now.Year, DateTime.Now.Month);
            ViewData["pagesize"] = Config.Get(Provider).blogpage;
            this.title = string.Format("{0} - {1}", Config.Get(Provider).title, Config.Get(Provider).intro);
            return View("list", "blog");
        }

        public ActionResult Archive(int? year, int? month, int? day, int? page)
        {
            year = year ?? DateTime.Now.Year;
            month = month ?? 1;
            page = page ?? 1;
            day = day ?? 0;
            try
            {
                if (month.Value < 1)
                {
                    FillArchive(year.Value, page.Value);
                }
                else if (day.Value < 1)
                {
                    FillArchive(year.Value, month.Value, page.Value);
                }
                else
                {
                    FillArchive(year.Value, month.Value, day.Value, page.Value);
                }
            }
            catch (Exception ex)
            {
                return Message("获取日志数据错误", ex.Message, new System.Web.Routing.RouteValueDictionary(new { controller = "blog", action = "index" }), "返回首页", MessageIcon.Error);
            }
            title = "查看日志存档 - " + Config.Get(Provider).title;
            return View("list", "blog");
        }

        public ActionResult View(int? id, int? page)
        {
            if (!id.HasValue)
                throw new ArgumentNullException("blogid");
            page = page ?? 1;
            lb_blog blog = Blog.Get(Provider, id.Value);
            if (blog == null)
            {
                return Message("获取日志数据错误", "无法获取该日志数据,该日志不存在或者已经被删除", new System.Web.Routing.RouteValueDictionary(new { controller = "blog", action = "index" }), "返回首页", MessageIcon.Error);
            }
            if (!blog.isshow)
            {
                if (blog.postuser != Membership.User.name)
                {
                    return Message("您无权查看该日志", "对不起,您无权查看该日志.", MessageIcon.Error);
                }
            }
            ViewData.Model = blog;
            if (blog.commentnum > 0)
            {
                ViewData["blogcomments"] = LevenBlog.Core.Service.Comment.Get(Provider, blog.id, Config.Get(Provider).commentpage, page.Value, CommentState.Show);
                ViewData["recordcount"] = LevenBlog.Core.Service.Comment.Count(Provider, blog.id, CommentState.Show);
            }
            else
            {
                ViewData["blogcomments"] = new List<lb_comment>();
                ViewData["recordcount"] = 0;
            }
            ViewData["aboutblogs"] = Blog.GetAbout(Provider, blog.id);
            ViewData["calendardata"] = CalendarCache.Get(Provider, DateTime.Now.Year, DateTime.Now.Month);
            ViewData["pagesize"] = Config.Get(Provider).commentpage;
            title = blog.title + " - " + Config.Get(Provider).title;
            return View("view", "blog");
        }

        public ActionResult Write()
        {
            if (!(Membership.Authority as Authority).Post)
                return Message("您无权进行该操作", "对不起,您无权进行该操作.", MessageIcon.Error);
            IList<lb_category> postCategories = Category.Get(Provider).Where(c => !c.isurl).OrderBy(c => c.order).ToList();
            if (postCategories.Count < 1)
                return Message("无可用分类", "无可用分类,请先进入后台添加blog分类.", MessageIcon.Error);
            ViewData["postcategories"] = postCategories;
            title = "撰写新日志 - " + Config.Get(Provider).title;
            return View("write");
        }

        public ActionResult Upload()
        {
            Authority authority = Membership.Authority as Authority;
            if (!authority.Upload)
                ViewData["uploadmessage"] = "对不起,您无权上传文件.";
            else if (Request.Form.Count > 0)
            {
                try
                {
                    lb_config config = Config.Get(Provider);
                    int maxLength = config.uploadsize > authority.UploadSize ? authority.UploadSize : config.uploadsize;
                    FileUpload fileUpload = new FileUpload(ControllerContext.HttpContext);
                    fileUpload.MaxLength = maxLength;
                    fileUpload.Type = config.uploadfiles;
                    fileUpload.UploadPath = config.uploadpath;
                    fileUpload.Save();
                    lb_file file = new lb_file();
                    file.name = fileUpload.SaveName;
                    file.path = fileUpload.SavePath;
                    file.type = fileUpload.ExtName;
                    file.hits = 0;
                    file.intro = fileUpload.PostName;
                    file.time = DateTime.Now;
                    file = LevenBlog.Core.Service.File.InsertAndGet(Provider, file);
                    ViewData["filename"] = string.Format("{0}/{1}.{2}", file.path, file.name, file.type);
                    ViewData["fileid"] = file.id;
                    ViewData["fileurl"] = Url.Action("file", "blog", new { id = file.id });
                    ViewData["uploadmessage"] = "<a href=\"{$backurl}\" title=\"返回继续\">文件上传成功,返回继续操作</a>";
                }
                catch (Exception ex)
                {
                    ViewData["uploadmessage"] = string.Format("<a href=\"{{$backurl}}\" title=\"返回重新操作\">文件上传错误,{0}</a>", ex.Message);
                }
            }
            return View("upload");
        }

        public ActionResult Post()
        {
            if (!(Membership.Authority as Authority).Post)
                return Message("您无权进行该操作", "对不起,您无权进行该操作.", MessageIcon.Error);
            string title, intro, content, tags, come, comeurl;
            int category = -1;
            bool islock = false;
            bool istemp = false;
            bool istop = false;
            title = Request.Form["title"];
            intro = Request.Form["intro"];
            content = Request.Form["content"];
            tags = Request.Form["tags"] == null ? string.Empty : Request.Form["tags"];
            come = Request.Form["come"];
            comeurl = Request.Form["comeurl"];
            int.TryParse(Request.Form["category"], out category);
            bool.TryParse(Request.Form["istemp"], out istemp);
            bool.TryParse(Request.Form["islock"], out islock);
            bool.TryParse(Request.Form["istop"], out istop);
            string message = string.Empty;
            if (string.IsNullOrEmpty(title))
            {
                message += "您提交的标题为空.<br />";
            }
            if (string.IsNullOrEmpty(content))
            {
                message += "您提交的正文为空.<br />";
            }
            if (string.IsNullOrEmpty(intro))
            {
                message += "您提交的简介为空.<br />";
            }
            if (string.IsNullOrEmpty(come))
            {
                message += "文章来源为空.<br />";
            }
            if (string.IsNullOrEmpty(comeurl))
            {
                message += "来源地址为空.<br />";
            }
            if (category < 1)
            {
                message += "分类选择错误.<br />";
            }
            if (!string.IsNullOrEmpty(message))
            {
                return Message("您提交的数据错误", message, MessageIcon.Error);
            }
            lb_blog blog = new lb_blog();
            blog.categoryid = category;
            blog.come = come.HtmlEncode();
            blog.comeurl = comeurl.HtmlEncode();
            blog.content = content;
            blog.intro = intro;
            blog.isedit = false;
            blog.islock = islock;
            blog.isshow = !istemp;
            blog.istop = istop;
            blog.postuser = Membership.User.name;
            blog.tags = tags;
            blog.title = title;
            blog.mails = Membership.User.id + "|";
            Blog.Insert(Provider, blog);
            ObjectCache.RegexRemove(".*blog.*");
            CalendarCache.Delete(blog.posttime.Year, blog.posttime.Month);
            return Message("撰写新Blog成功.", "恭喜您,您撰写的新的Blog成功.", new { controller = "blog", action = "index" }, "返回首页查看", MessageIcon.Message);
        }

        public ActionResult CommentPost(int? id)
        {
            id = id ?? 0;
            if (id.Value < 0)
                return Message("错误的日志编号", "您提交了一个错误的日志编号.", MessageIcon.Error);
            if (!(Membership.Authority as Authority).Comment)
                return Message("权限错误", "对不起,您无权发表评论.", MessageIcon.Error);
            string username, password, code, content;
            bool withinfo = false;
            bool withhtml = false;
            username = Request.Form["username"];
            password = Request.Form["password"];
            code = Request.Form["code"];
            content = Request.Form["content"];
            bool.TryParse(Request.Form["userinfo"], out withinfo);
            bool.TryParse(Request.Form["html"], out withhtml);
            if (string.IsNullOrEmpty(username))
                return Message("用户名为空", "您未填写用户名信息.", MessageIcon.Error);
            else if (username.Trim().Length < 1)
                return Message("用户名为空", "您未填写用户名信息.", MessageIcon.Error);
            if (string.IsNullOrEmpty(code))
                return Message("验证码为空", "您未填写验证码.", MessageIcon.Error);
            else if (code.Trim().Length< 1)
                return Message("验证码为空", "您未填写验证码.", MessageIcon.Error);
            if (string.IsNullOrEmpty(content))
                return Message("评论内容为空", "您提交的评论内容为空.", MessageIcon.Error);
            else if (content.Trim().Length < 1)
                return Message("评论内容为空", "您提交的评论内容为空.", MessageIcon.Error);
            HttpCookie codeCookie = Request.Cookies.Get(WebConfig.PrefixKey + "CheckCode");
            if (codeCookie == null)
            {
                return Message("验证码过期", "验证码过期,请返回重新输入.", MessageIcon.Error);
            }
            else
            {
                if (code.ToLower().ToMD5() != codeCookie.Value)
                    return Message("验证码错误", "验证码输入错误,请返回重新上输入.", MessageIcon.Error);
                else
                    Response.Cookies.Remove(WebConfig.PrefixKey + "CheckCode");
            }
            username = username.Trim();
            code = code.Trim();
            lb_blog blog = Blog.Get(Provider, id.Value);
            if (blog == null)
            {
                return Message("无法评论该日志", "您评论的日志不存在或者已经被删除.", MessageIcon.Error);
            }
            if (blog.islock)
            {
                return Message("无法评论该日志", "该日志禁止评论.", MessageIcon.Error);
            }
            lb_comment comment = new lb_comment();
            comment.blogid = blog.id;
            if (Membership.User.id < 0)
            {
                if (string.IsNullOrEmpty(password))
                {
                    if (Membership.CheckUser(username))
                    {
                        return Message("您无权使用该用户名.", "该用户名已经被注册,请登陆后使用.", MessageIcon.Error);
                    }
                }
                else
                {
                    if (!Membership.Login(username, password.Trim()))
                    {
                        return Message("用户信息错误", "您提交的用户名或者密码错误,无法登陆.", MessageIcon.Error);
                    }
                }
            }
            else
            {
                if (Membership.User.name != username)
                {
                    return Message("错误的用户名", "您提交的用户名和登陆信息不符.", MessageIcon.Error);
                }
            }
            comment.user = username;
            comment.userid = Membership.User.id;
            comment.title = string.Empty;
            comment.posttime = DateTime.Now;
            comment.mail = string.Empty;
            comment.ismailnew = false;
            comment.ip = Fetch.UserIp;
            if ((Membership.Authority as Authority).PostHtml && withhtml)
            {
                comment.content = content.ToSafeHtml();
            }
            else
            {
                comment.content = content.HtmlEncode();
            }
            if (Membership.User.id > 0)
            {
                if (withinfo)
                {
                    Membership.LoadFull();
                    comment.content = string.Format("{0}\r\n<div class=\"userinfo\">{1}</div>", comment.content, Membership.User.userinfo.signature);
                }
                comment.ismailnew = Request.Form["mailnew"].ToBoolean();
            }
            if (comment.content.Length > (Membership.Authority as Authority).CommentLength)
            {
                return Message("您的评论内容太长", "您提交的评论内容超过系统的限制.", MessageIcon.Error);
            }
            //过滤非法字符
            string[] bakchars = Config.Get(Provider).badchars.Split('|');
            StringBuilder sb = new StringBuilder(comment.content);
            foreach (string bc in bakchars)
            {
                sb.Replace(bc, "*");
            }
            comment.content = sb.ToString();
            if ((Membership.Authority as Authority).CommentNeedVerify)
            {
                comment.isshow = false;
            }
            else
            {
                comment.isshow = true;
            }
            LevenBlog.Core.Service.Comment.Insert(Provider, comment);
            ObjectCache.RegexRemove(".*blog.*");
            ObjectCache.RegexRemove(".*comment.*");
            if ((Membership.Authority as Authority).CommentNeedVerify)
                return Message("提交评论成功.", "恭喜您,您的评论提交,请等待管理员审核.", new { controller = "blog", action = "view", id = blog.id.ToString() }, "返回查看结果", MessageIcon.Message);
            else
                return Message("提交评论成功.", "恭喜您,您的评论发布成功.", new { controller = "blog", action = "view", id = blog.id.ToString() }, "返回查看结果", MessageIcon.Message);

        }

        public ActionResult Edit(int? id)
        {
            id = id ?? 0;
            if (!(Membership.Authority as Authority).Edit)
                return Message("无权编辑该Blog", "对不起,您无权编辑该Blog.", MessageIcon.Error);
            lb_blog editBlog = Blog.Get(Provider, id.Value);
            if (editBlog == null)
                return Message("无法编辑该Blog", "无法编辑,该Blog不存在或者已经被删除.", new { controller = "blog", action = "index" }, "返回首页查看", MessageIcon.Error);
            if (!(Membership.Authority as Authority).Super && editBlog.postuser != Membership.User.name)
                return Message("无权编辑该Blog", "对不起,您无权编辑该Blog.", MessageIcon.Error); 
            ViewData.Model = editBlog;
            IList<lb_category> postCategories = Category.Get(Provider).Where(c => !c.isurl).OrderBy(c => c.order).ToList();
            if (postCategories.Count < 1)
                Message("无可用分类", "无可用分类,请先进入后台添加blog分类.", MessageIcon.Error);
            ViewData["postcategories"] = postCategories;
            title = "编辑日志 - " + editBlog.title;
            return View("edit");
        }

        public ActionResult EditPost(int? id)
        {
            id = id ?? 0;
            if (!(Membership.Authority as Authority).Edit)
                return Message("无权编辑该Blog", "对不起,您无权编辑该Blog.", MessageIcon.Error);
            lb_blog blog = Blog.Get(Provider, id.Value);
            if (blog == null)
                return Message("无法编辑该Blog", "无法编辑,该Blog不存在或者已经被删除.", new { controller = "blog", action = "index" }, "返回首页查看", MessageIcon.Error);
            if (!(Membership.Authority as Authority).Super && blog.postuser != Membership.User.name)
                return Message("无权编辑该Blog", "对不起,您无权编辑该Blog.", MessageIcon.Error); 
            string title, intro, content, tags, come, comeurl;
            int category = -1;
            bool islock = false;
            bool istemp = false;
            bool istop = false;
            title = Request.Form["title"];
            intro = Request.Form["intro"];
            content = Request.Form["content"];
            tags = Request.Form["tags"] == null ? string.Empty : Request.Form["tags"];
            come = Request.Form["come"];
            comeurl = Request.Form["comeurl"];
            int.TryParse(Request.Form["category"], out category);
            bool.TryParse(Request.Form["istemp"], out istemp);
            bool.TryParse(Request.Form["islock"], out islock);
            bool.TryParse(Request.Form["istop"], out istop);
            string message = string.Empty;
            if (string.IsNullOrEmpty(title))
            {
                message += "您提交的标题为空.<br />";
            }
            if (string.IsNullOrEmpty(content))
            {
                message += "您提交的正文为空.<br />";
            }
            if (string.IsNullOrEmpty(intro))
            {
                message += "您提交的简介为空.<br />";
            }
            if (string.IsNullOrEmpty(come))
            {
                message += "文章来源为空.<br />";
            }
            if (string.IsNullOrEmpty(comeurl))
            {
                message += "来源地址为空.<br />";
            }
            if (category < 1)
            {
                message += "分类选择错误.<br />";
            }
            if (!string.IsNullOrEmpty(message))
            {
                return Message("您提交的数据错误", message, MessageIcon.Error);
            }
            blog.categoryid = category;
            blog.come = come.HtmlEncode();
            blog.comeurl = comeurl.HtmlEncode();
            blog.content = content;
            blog.intro = intro;
            blog.isedit = false;
            blog.islock = islock;
            blog.isshow = !istemp;
            blog.istop = istop;
            blog.isedit = true;
            blog.edituser = Membership.User.name;
            blog.edittime = DateTime.Now;
            blog.tags = tags;
            blog.title = title;
            Blog.Update(Provider, blog);
            ObjectCache.RegexRemove(".*blog.*");
            ObjectCache.RegexRemove(".*cate.*");
            return Message("修改Blog成功.", "恭喜您,您修改的Blog提交成功..", new { controller = "blog", action = "view", id=blog.id.ToString() }, "返回查看结果", MessageIcon.Message);
        }

        public ActionResult Delete(int? id)
        {
            id = id ?? 0;
            if (id.Value < 1)
                return Message("错误的blog信息", "您请求的blog错误.", MessageIcon.Error);
            if (!(Membership.Authority as Authority).Delete)
            {
                return Message("您无权进行该操作", "您无权对Blog进行删除动作.", MessageIcon.Error);
            }
            lb_blog blog = Blog.Get(Provider, id.Value);
            if (blog == null)
            {
                return Message("无法删除该Blog", "无法删除该Blog,该Blog不存在或者已经被删除.", MessageIcon.Error);
            }
            Blog.Delete(Provider, blog.id);
            ObjectCache.RegexRemove(".*blog.*");
            ObjectCache.RegexRemove(".*cate.*");
            ObjectCache.RegexRemove(".*comment.*");
            return Message("删除Blog成功.", string.Format("恭喜,您成功删除了ID为{0}的Blog.", blog.id), new { controller = "blog", action = "index" }, "返回首页", MessageIcon.Message);
        }

        public ActionResult CommentDelete(int? id)
        {
            id = id ?? 0;
            if (id.Value < 1)
                return Message("请求错误", "您请求了错误的评论信息", MessageIcon.Error);
            if (!(Membership.Authority as Authority).ManageComment)
                return Message("您无权进行该操作", "您无权对评论进行删除动作.", MessageIcon.Error);
            lb_comment comment = LevenBlog.Core.Service.Comment.Get(Provider, id.Value);
            if (comment == null)
            {
                return Message("无法删除该评论", "无法删除该评论,该评论不存在或者已经被删除.", MessageIcon.Error);
            }
            LevenBlog.Core.Service.Comment.Delete(Provider, id.Value);
            ObjectCache.RegexRemove(".*blog.*");
            ObjectCache.RegexRemove(".*cate.*");
            ObjectCache.RegexRemove(".*comment.*");
            return Message("删除评论成功.", string.Format("恭喜,您成功删除了ID为{0}的评论.", comment.id), new { controller = "blog", action = "view", id=comment.blogid }, "返回查看", MessageIcon.Message);
        }

        public ActionResult Draft(int? page)
        {
            page = page ?? 1;
            ViewData["recordcount"] = Blog.CountFromUser(Provider, Membership.User.name.SqlEncode(), BlogState.UnShow);
            ViewData.Model = Blog.GetFromUser(Provider, Membership.User.name.SqlEncode(), Config.Get(Provider).blogpage, page.Value, BlogState.UnShow);
            ViewData["calendardata"] = CalendarCache.Get(Provider, DateTime.Now.Year, DateTime.Now.Month);
            ViewData["pagesize"] = Config.Get(Provider).blogpage;
            this.title = string.Format("查看日志草稿箱 - {0}", Config.Get(Provider).title);
            return View("list", "blog");
        }

        public ActionResult Search(string q, int? page)
        {
            if (string.IsNullOrEmpty(q))
                return Message("关键字为空", "搜索关键字不能为空.", MessageIcon.Error);
            page = page ?? 1;
            ViewData["recordcount"] = Blog.CountFromSearchTitle(Provider, q.SqlEncode(), BlogState.Show);
            var model = Blog.SearchTitle(Provider, q.SqlEncode(), Config.Get(Provider).blogpage, page.Value, BlogState.Show);
            if (model.Count <= 0) {
                return Message("查询错误", "查询结果为空.", MessageIcon.Warning);
            }
            ViewData.Model = model;
            ViewData["calendardata"] = CalendarCache.Get(Provider, DateTime.Now.Year, DateTime.Now.Month);
            ViewData["pagesize"] = Config.Get(Provider).blogpage;
            this.title = string.Format("搜索关键字:{0} - {1}", q, Config.Get(Provider).title);
            return View("list", "blog");
        }

        public ActionResult Tag(string q, int? page)
        {
            page = page ?? 1;
            ViewData["recordcount"] = Blog.CountFromSearchTags(Provider,q.SqlEncode(), BlogState.Show);
            var model = Blog.SearchTags(Provider, q.SqlEncode(), Config.Get(Provider).blogpage, page.Value, BlogState.Show);
            if (model.Count <= 0) {
                return Message("系统信息", "没有与该Tag相关的日志.", MessageIcon.Error);
            }
            ViewData.Model = model;
            ViewData["calendardata"] = CalendarCache.Get(Provider, DateTime.Now.Year, DateTime.Now.Month);
            ViewData["pagesize"] = Config.Get(Provider).blogpage;
            this.title = string.Format("查看Tag:{0}的日志 - {1}", q, Config.Get(Provider).title);
            return View("list", "blog");
        }

        public ActionResult Comment(int? page)
        {
            page = page ?? 1;
            ViewData["recordcount"] = LevenBlog.Core.Service.Comment.Count(Provider, CommentState.Show);
            ViewData.Model = LevenBlog.Core.Service.Comment.Get(Provider, Config.Get(Provider).commentpage, page.Value, CommentState.Show);
            ViewData["calendardata"] = CalendarCache.Get(Provider, DateTime.Now.Year, DateTime.Now.Month);
            ViewData["pagesize"] = Config.Get(Provider).commentpage;
            this.title = string.Format("查看用户评论 - {0}", Config.Get(Provider).title);
            return View("commnet", "blog");
        }

        public ActionResult File(int? id)
        {
            //if (Fetch.IsGetFromAnotherDomain)
            //    return ResponseFile(-1);
            if (!id.HasValue)
                return Message("错误的文件信息", "无法找到指定的文件.", MessageIcon.Error);
            return ResponseFile(id.Value);
        }

        public ActionResult Rss(int? category, int? page)
        {
            category = category ?? -1;
            page = page ?? 1;
            FeedResult rssResult = new FeedResult(Provider);
            rssResult.CategoryID = category.Value;
            rssResult.Page = page.Value;
            return rssResult;
        }

        public ActionResult Atom(int? category, int? page)
        {
            category = category ?? -1;
            page = page ?? 1;
            FeedResult atomResult = new FeedResult(Provider);
            atomResult.Type = FeedType.Atom;
            atomResult.CategoryID = category.Value;
            atomResult.Page = page.Value;
            return atomResult;
        }

        public ActionResult Code()
        {
            return new CheckCodeResult();
        }

        public ActionResult Tags(int? page)
        {
            page = page ?? 1;
            int pagesize = 100;
            ViewData.Model = LevenBlog.Core.Service.Tag.GetOrderByHot(Provider, pagesize, page.Value);
            ViewData["pagesize"] = pagesize;
            ViewData["recordcount"] = LevenBlog.Core.Service.Tag.Count(Provider);
            ViewData["calendardata"] = CalendarCache.Get(Provider, DateTime.Now.Year, DateTime.Now.Month);
            title = string.Format("按Tag浏览 - {0}", Config.Get(Provider).title);
            return View("tags", "blog");
        }

        public ActionResult SubTags(int? num)
        {
            num = num ?? 20;
            IList<lb_tag> tags = LevenBlog.Core.Service.Tag.GetOrderByHot(Provider, num.Value, 1);
            ViewData.Model = tags;
            return View("subtags");
        }

        public ActionResult Link()
        {
            title = Config.Get(Provider).title + " - 友情链接";
            ViewData.Model = FriendLink.Get(Provider).Where(f => f.isshow == true).ToList();
            ViewData["calendardata"] = CalendarCache.Get(Provider, DateTime.Now.Year, DateTime.Now.Month);
            return View("link", "blog");
        }

        public ActionResult LinkPost()
        {
            string name = Request.Form["linkname"];
            string url = Request.Form["linkurl"];
            string image = Request.Form["linkimage"];
            string code = Request.Form["code"];
            name = name == null ? string.Empty : name.Trim();
            url = url == null ? string.Empty : url.Trim();
            image = image == null ? string.Empty : image.Trim();
            code = code == null ? string.Empty : code.Trim();
            if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(url))
                return Message("数据输入不完整", "连接名或者链接地址为空,请重新填写.", MessageIcon.Error);
            if (string.IsNullOrEmpty(code))
                return Message("未输入验证码", "请输入验证码.", MessageIcon.Error);
            HttpCookie codeCookie = Request.Cookies.Get(WebConfig.PrefixKey + "CheckCode");
            if (codeCookie == null)
            {
                return Message("验证码过期", "验证码过期,请返回重新输入.", MessageIcon.Error);
            }
            else
            {
                if (code.ToLower().ToMD5() != codeCookie.Value)
                    return Message("验证码错误", "验证码输入错误,请返回重新上输入.", MessageIcon.Error);
                else
                    Response.Cookies.Remove(WebConfig.PrefixKey + "CheckCode");
            }
            lb_friendlink link = new lb_friendlink();
            link.name = name;
            link.url = url;
            link.image = image;
            link.intro = name;
            link.isimg = false;
            link.isshow = false;
            FriendLink.Insert(Provider, link);
            return Message("申请提交成功", "恭喜,您的申请成功提交,请耐心等待管理员审核.", new { controller = "blog", action = "link" }, "返回", MessageIcon.Message);
        }

        public ActionResult TrackBackXSL()
        {
            TrackXSLResult xslResult = new TrackXSLResult("/blog/trackback.xsl");
            xslResult.Provider = Provider;
            return xslResult;
        }

        public ActionResult Track(int? id)
        {
            id = id ?? 0;
            TrackResponseResult trackResult = new TrackResponseResult(id.Value, TrackType.View);
            trackResult.Provider = Provider;
            return trackResult;
        }

        public ActionResult TrackBack(int? id)
        {
            id = id ?? 0;
            if (!(Membership.Authority as Authority).Track)
                return Message("权限错误", "对不起,您无权引用该文章.", MessageIcon.Error);
            TrackResponseResult trackResult = new TrackResponseResult(id.Value, TrackType.Post);
            trackResult.Provider = Provider;
            return trackResult;
        }

        public ActionResult Info()
        {
            return Json(new { Url = Fetch.PublicInfoUrl });
        }

        public ActionResult Jump(string actionName, int? category, int? page, int? id, string q) {
            if (String.IsNullOrEmpty(actionName))
                actionName = "index";
            RouteValueDictionary route = new RouteValueDictionary();
            if (category != null) {
                route.Add("category", category.Value);
            }
            if (page != null) {
                route.Add("page", page.Value);
            }
            if (id != null) {
                route.Add("id", id.Value);
            }
            if (!String.IsNullOrEmpty(q)) {
                route.Add("q", q);
            }
            return RedirectToAction(actionName, route);
        }

        #region 存档日志有关的方法

        [NonAction]
        private void FillArchive(int year, int page)
        {
            DateTime startTime = new DateTime(year, 1, 1);
            DateTime endTime = startTime.AddYears(1);
            FillArchive(startTime, endTime, page);
        }

        [NonAction]
        private void FillArchive(int year, int month, int page)
        {
            DateTime startTime = new DateTime(year, month, 1);
            DateTime endTime = startTime.AddMonths(1);
            FillArchive(startTime, endTime, page);
        }

        [NonAction]
        private void FillArchive(int year, int month, int day, int page)
        {
            DateTime startTime = new DateTime(year, month, day);
            DateTime endTime = startTime.AddDays(1);
            FillArchive(startTime, endTime, page);
        }

        [NonAction]
        private void FillArchive(DateTime startTime, DateTime endTime, int page)
        {
            int recordcount = Blog.CountFromDateTime(Provider, startTime, endTime, BlogState.Show);
            if (recordcount < 1)
                throw new Exception("你提交的时间段没有日志.");
            ViewData["recordcount"] = recordcount;
            ViewData.Model = Blog.Get(Provider, startTime, endTime, Config.Get(Provider).blogpage, page, BlogState.Show);
            ViewData["selectdate"] = startTime;
            ViewData["calendardata"] = CalendarCache.Get(Provider, startTime.Year, startTime.Month);
        }

        #endregion
    }
}
